package com.v512.guestbook;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AddMessageServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String driver = "org.gjt.mm.mysql.Driver";
		String url = "jdbc:mysql://127.0.0.1:3306/usermanager";
		String username = "root";
		String password = "123456";
		String sql = "insert into guestbook(name,email,phone,title,content,time) value(?,?,?,?,?,?)";// 插入数据
		int result = 0;
		
		request.setCharacterEncoding("utf-8");
		String name = request.getParameter("name");
		String title = request.getParameter("title");
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		out.println("<html>");
		out.println("<head><title>add message</title></head>");
		out.println("<body>");
		if (StringUtil.validateNull(name)) {
			out.println("对不起，姓名不能为空，请重新输入！");
			out.println("<a href='/guestbook/addMessage.html'>添加留言</a><br>");
		} else if (StringUtil.validateNull(title)) {
			out.println("对不起，姓名不能为空，请重新输入！");
			out.println("<a href='/guestbook/addMessage.html'>添加留言</a><br>");
		}
		try {
			Class.forName(driver);
			Connection conn = DriverManager.getConnection(url, username, password);
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setString(1, StringUtil.filterHtml(request.getParameter("name")));
			ps.setString(2, StringUtil.filterHtml(request.getParameter("email")));
			ps.setString(3, StringUtil.filterHtml(request.getParameter("phone")));
			ps.setString(4, StringUtil.filterHtml(title));
			ps.setString(5, request.getParameter("content"));
			
			SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd hh:mm:ss");
			ps.setString(6, sdf.format(new java.util.Date()));
			result = ps.executeUpdate();
			ps.close();
			conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (result == 0 ) {
			out.println("对不起，姓名不能为空，请重新输入！");
			out.println("<a href='/guestbook/addMessage.html'>添加留言</a><br>");
		} else {
			out.println("恭喜，留言添加成功！");
			out.println("<a href='/guestbook/servlet/getMessage'>获取留言</a><br>");
		}
		out.println("</body>");
		out.println("</html>");
		out.flush();
		out.close();
	}

}
